package com.lijinquan.springcloud.controller;

import cn.lijinquan.p2p.entites.ResultMap;
import cn.lijinquan.p2p.entites.UserAcount;
import com.lijinquan.springcloud.constants.FrontStatusConstants;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 投资
 * Created by lijinquan on 2019/10/4.
 */
@RestController
public class InvestmentController {

    private static final String REST_URL_PREFIX = "http://P2P-WEB/";
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/investment/checkAccount")
    public ResultMap<Boolean> checkAccount(HttpServletRequest request){
        ResultMap<Boolean> rm = new ResultMap<>();
        String account = request.getParameter("account");
        String token = request.getHeader("token");
        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setStatus(FrontStatusConstants.NOT_LOGGED_IN);// 用户未登录
            return rm;
        }
        Integer userId = (Integer) tokenmap.get("id");
        UserAcount uc = restTemplate.getForObject(REST_URL_PREFIX + "account/accountHomepage/" + userId, UserAcount.class);

        /**
         *  BigDecimal..compareTo -1 小于   0  等于  1  大于
         */
        if(uc!=null && uc.getBalance().compareTo(new BigDecimal(Integer.valueOf(account)))!=-1){
            rm.setBody(true);
        }else {
            rm.setStatus(FrontStatusConstants.NOT_SUFFICIENT_FUNDS);
            rm.setBody(false);
            return rm;
        }

        return rm;

    }

}
